//
//  CardManagement.m
//  ManageMoney
//
//  Created by 大明 on 16/4/22.
//  Copyright © 2016年 db. All rights reserved.
//

#import "CardManagement.h"
#import "AddCashCard.h"
#import "AddCreditCardVC.h"
#import "CardManagementCell.h"
#import "PayMethodsController.h"

@interface CardManagement ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *addCashCardArray;
    NSMutableArray *addCreditCardArray;
    UIButton *cardTypeLabel;
}
@property (weak, nonatomic) IBOutlet UITableView *cardManageTable;
@property (weak, nonatomic) IBOutlet UIButton *addCardBtn;

@end

@implementation CardManagement

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _cardManageTable.delegate = self;
    _cardManageTable.dataSource = self;
    //footview
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
    _cardManageTable.tableFooterView = footerView;
    
    if ([_addCardStr isEqualToString:@"1"]) {
        self.title = @"卡管理";
        [_addCardBtn setTitle:@"添加储蓄卡" forState:UIControlStateNormal];
    }else if ([_addCardStr isEqualToString:@"2"]){
        [_addCardBtn setTitle:@"添加信用卡" forState:UIControlStateNormal];
        self.title = @"信用卡列表";
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self cardmanagement];
}

-(void)cardmanagement{
    NSString *cardmanagementUrl;
     NSMutableDictionary *pramas  = [[NSMutableDictionary alloc]init];
    pramas[@"customerNo"] = _customerNoStr;

    if ([_addCardStr isEqualToString:@"1"]) {//储蓄卡
        addCashCardArray = [[NSMutableArray alloc]init];
        [SVProgressHUD show];
        cardmanagementUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/queryBankCardList.do"];
       
            }else if([_addCardStr isEqualToString:@"2"]){//信用卡
        addCreditCardArray = [[NSMutableArray alloc]init];
        [SVProgressHUD show];
        cardmanagementUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/queryCreditCardList.do"];
        
    }
    
    
    [HWHttpTool post:cardmanagementUrl params:pramas success:^(id json) {
        [SVProgressHUD dismiss];
        NSLog(@"%@",json);
        
        NSDictionary *dic = json;
        if ([dic[@"responseCode"] intValue] == 200) {
            if ([_addCardStr isEqualToString:@"1"]) {
                addCashCardArray = dic[@"responseObj"];
            }else if ([_addCardStr isEqualToString:@"2"]){
                addCreditCardArray = dic[@"responseObj"];
            }
            
            
            
            [_cardManageTable reloadData];
            
            
        }else
        {
            [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - tableview的代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_addCardStr isEqualToString:@"1"]) {
        return [addCashCardArray count];
    }else if([_addCardStr isEqualToString:@"2"]){
        return [addCreditCardArray count];
    }else{
        return 0;
    }
//    return 3;
    
}

//修改tableview的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    
    static NSString *indentifier = @"CardManagementCell";
    CardManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (cell==nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CardManagementCell" owner:self options:nil][0];
    }

    

    
    NSDictionary *dic;
    if ([_addCardStr isEqualToString:@"1"]) {
        dic= addCashCardArray[indexPath.row];
        
        
        if ([CheckNull(dic[@"KHYH"]) isEqualToString:@"中国农业银行"]) {
            cell.iconImage.image = [UIImage imageNamed:@"ic_nyyh"];
        }else if ([CheckNull(dic[@"KHYH"]) isEqualToString:@"中国建设银行"]){
            cell.iconImage.image = [UIImage imageNamed:@"ic_jsyh"];
        }else if ([CheckNull(dic[@"KHYH"]) isEqualToString:@"中国银行"]){
            cell.iconImage.image = [UIImage imageNamed:@"ic_zgyh"];
        }else if ([CheckNull(dic[@"KHYH"]) isEqualToString:@"中国工商银行"]){
            cell.iconImage.image = [UIImage imageNamed:@"ic_gsyh"];
        }
        
        cell.cardNameLabel.text = CheckNull(dic[@"KHYH"]);
        
        if ([CheckNull(dic[@"default_flag"]) isEqualToString:@"1"]) {
            [cell.cardTypeBtn setTitle:@"主卡" forState:UIControlStateNormal];
            [cell.cardTypeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            cell.cardTypeBtn.userInteractionEnabled = NO;
        }else if([CheckNull(dic[@"default_flag"]) isEqualToString:@"0"]){
            [cell.cardTypeBtn setTitle:@"设为主卡" forState:UIControlStateNormal];
            cell.cardTypeBtn.tag = 200+indexPath.row;
            [cell.cardTypeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            cell.cardTypeBtn.userInteractionEnabled = YES;
            [cell.cardTypeBtn addTarget:self action:@selector(SetgivePriorityToCard:) forControlEvents:UIControlEventTouchUpInside];
        }
        NSString *cardNum =  [NSString stringWithFormat:@"%@",CheckNull(dic[@"YHZH"])];
        NSUInteger strNum = cardNum.length;
        NSString *str = [cardNum substringWithRange:NSMakeRange(strNum-4, 4)];
        cell.cardIdLabel.text = [NSString stringWithFormat:@"**** **** ****%@",str];
        [cell.deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        cell.deleteBtn.tag = 100 +indexPath.row;
        [cell.deleteBtn addTarget:self action:@selector(deleteClcik:) forControlEvents:UIControlEventTouchUpInside];
    }else if([_addCardStr isEqualToString:@"2"]){
        dic = addCreditCardArray[indexPath.row];
        
        cell.iconImage.image = [UIImage imageNamed:@"ic_yinlian"];
        cell.cardNameLabel.text = CheckNull(dic[@"card_name"]);
        [cell.cardTypeBtn setTitle:@"(已认证)" forState:UIControlStateNormal];
        [cell.cardTypeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        
        NSString *cardNum =  [NSString stringWithFormat:@"%@",CheckNull(dic[@"card_no"])];
        NSUInteger strNum = cardNum.length;
        NSString *str = [cardNum substringWithRange:NSMakeRange(strNum-4, 4)];
        cell.cardIdLabel.text = [NSString stringWithFormat:@"**** **** ****%@",str];
        [cell.deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        cell.deleteBtn.tag = 100 +indexPath.row;
        [cell.deleteBtn addTarget:self action:@selector(deleteClcik:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if ([_addCardStr isEqualToString:@"2"]) {
        NSDictionary *dict = addCreditCardArray[indexPath.row];
        PayMethodsController *ctr = [[PayMethodsController alloc] initWithNibName:@"PayMethodsController" bundle:nil];
        ctr.title = @"账户充值";
        ctr.payType = 0;
        ctr.PayMethodsStr = CheckNull(dict[@"card_no"]);
        [self.navigationController pushViewController:ctr animated:YES];
    }
    
}

-(void)SetgivePriorityToCard:(UIButton *)sender
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定设为主卡？" preferredStyle:UIAlertControllerStyleAlert];
    
    
    // 添加按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
//        NSLog(@"点击了确定按钮");
        NSDictionary *dic;
//        if ([_addCardStr isEqualToString:@"1"]) {
            dic= addCashCardArray[sender.tag-200];
//        }
       
        NSMutableDictionary *pramas  = [[NSMutableDictionary alloc]init];
        pramas[@"bankCardId"] = CheckNull(dic[@"id"]);
        pramas[@"customerNo"] = CheckNull(UserInfo[@"NUMBER"]);
        NSString *cardmanagementUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/updateMainBankCard.do"];
        [HWHttpTool post:cardmanagementUrl params:pramas success:^(id json) {
            [SVProgressHUD dismiss];
            NSLog(@"%@",json);
            
            NSDictionary *dic = json;
            if ([dic[@"responseCode"] intValue] == 200) {
                
                [self cardmanagement];
                
                
                
                [_cardManageTable reloadData];
                
                
            }else
            {
                [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [SVProgressHUD dismiss];
        }];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//        NSLog(@"点击了取消按钮");
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)deleteClcik:(UIButton *)sender{
    
    NSDictionary *dic;
    if ([_addCardStr isEqualToString:@"1"]) {
        dic= addCashCardArray[sender.tag-100];
    }else if([_addCardStr isEqualToString:@"2"]){
        dic = addCreditCardArray[sender.tag-100];
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除？" preferredStyle:UIAlertControllerStyleAlert];
    
    
    // 添加按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
        if ([_addCardStr isEqualToString:@"1"]) {//储蓄卡
            NSMutableDictionary *pramas  = [[NSMutableDictionary alloc]init];
            pramas[@"bankCardId"] = CheckNull(dic[@"id"]);
            pramas[@"customerNo"] = CheckNull(UserInfo[@"NUMBER"]);
            NSString *cardmanagementUrl = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/deleteBankCard.do"];
            [HWHttpTool post:cardmanagementUrl params:pramas success:^(id json) {
                [SVProgressHUD dismiss];
                NSLog(@"%@",json);
                
                NSDictionary *dic = json;
                if ([dic[@"responseCode"] intValue] == 200) {
                    
                    [self cardmanagement];
                    
                    
                    
                    [_cardManageTable reloadData];
                    
                    
                }else
                {
                    [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [SVProgressHUD dismiss];
            }];
            
        } else if([_addCardStr isEqualToString:@"2"]){//信用卡
            NSMutableDictionary *pramas  = [[NSMutableDictionary alloc]init];
            pramas[@"creditCardId"] = CheckNull(dic[@"id"]);
            NSString *cardmanagementUrl1 = [@"" stringByAppendingFormat:@"%@%@",hrtxUrl,@"fund/deleteCreditCard.do"];
            [HWHttpTool post:cardmanagementUrl1 params:pramas success:^(id json) {
                [SVProgressHUD dismiss];
                NSLog(@"%@",json);
                
                NSDictionary *dic = json;
                if ([dic[@"responseCode"] intValue] == 200) {
                    
                    [self cardmanagement];
                    
                    
                    
                    [_cardManageTable reloadData];
                    
                    
                }else
                {
                    [SVProgressHUD showErrorWithStatus:dic[@"responseMessage"]];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [SVProgressHUD dismiss];
            }];
        }

        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        //        NSLog(@"点击了取消按钮");
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
    
    
    
    

}


//添加卡
- (IBAction)addCardClcik:(id)sender {
    if ([_addCardStr isEqualToString:@"1"]) {
        AddCashCard *addcashCardvc = [[AddCashCard alloc]initWithNibName:@"AddCashCard" bundle:nil];
        [self.navigationController pushViewController:addcashCardvc animated:YES];
    }else if([_addCardStr isEqualToString:@"2"]){
        AddCreditCardVC *addcreditCardvc = [[AddCreditCardVC alloc]initWithNibName:@"AddCreditCardVC" bundle:nil];
        [self.navigationController pushViewController:addcreditCardvc animated:YES];
    }
}

@end
